#!/bin/bash


function usage()
{
    echo "usage :cmd [params]"
    echo "cmd:"
    echo "  help|-help|--help|-h|--h"
    echo "  online|status|restart|start|stop|recover|frestart|cleanlog|mem|reset dest [params]"
    echo "      dest:all|host.x|fast.sid|sid|minsid-maxsid"
    echo "  querylog sid userid page [date]"
    echo "  queryrecord sid openid page type"
    echo "  list [all|valid|sid]"
    echo "  update all|sid version"
    echo "  open sid"
    echo "  cleanMerged sid|minsid-maxsid"
}

info() {
    title=$1
    content=$2
    case "$decorator" in
    pure)
        echo -e "$title [$content] "$3
    ;;
    *)
        echo -e "\E[32m$title\E[0m \E[33m[$content]\E[0m "$3 
    ;;
    esac
}

warn() {
    title=$1
    content=$2
    case "$decorator" in
    pure)
        echo -e "$title [$content] "$3
    ;;
    *)
        echo -e "\E[32m$title\E[0m \E[31m[$content]\E[0m "$3 
    ;;
    esac
}

if (($# < 1)); then
    usage
    exit 1
fi

###########################################################################
online() {
    ip=$1
    sid=$2
    version=$3
    path=`./config/get.sh game.path $sid`
    result=`ssh $ip "source ~/.bash_profile; cd $path; ./auto_online; git log |head -n 1"`
    info "$title" "finish" "$result"

    if [ -n "$version" ]; then
        ./$process update $sid $version
    fi
}

status(){
    ip=$1
    sid=$2
    path=`./config/get.sh game.path $sid`
    result=`ssh $ip "source ~/.bash_profile; cd $path; ./manage $fullCmd; git log |head -n 1"`
    info "$title" "finish" "$result"
}

restart(){
    ip=$1
    sid=$2
    path=`./config/get.sh game.path $sid`
    result=`ssh $ip "source ~/.bash_profile; cd $path; ./manage $fullCmd; git log |head -n 1"`
    info "$title" "finish" "$result"
}

start(){
    ip=$1
    sid=$2
    path=`./config/get.sh game.path $sid`
    result=`ssh $ip "source ~/.bash_profile; cd $path; ./manage $fullCmd; git log |head -n 1"`
    info "$title" "finish" "$result"
}

stop(){
    ip=$1
    sid=$2
    path=`./config/get.sh game.path $sid`
    result=`ssh $ip "source ~/.bash_profile; cd $path; ./manage $fullCmd; git log |head -n 1"`
    info "$title" "finish" "$result"
}

recover() {
    ip=$1
    sid=$2

    path=`./config/get.sh game.path $sid`
    result=`ssh $ip "source ~/.bash_profile; cd $path; ./manage status | grep Lost"`
    if [ -z "$result" ]; then
        echo "Is Running"
        return
    fi
    
    online $ip $sid
}

frestart() {
    ip=$1
    sid=$2
    path=`./config/get.sh game.path $sid`
    result=`ssh $ip "source ~/.bash_profile; 
        cd $path; 
        ./manage pure.abort;
        ./manage pure.restart;"`
    info "$title" "finish" "$result"
}

cleanlog() {
    ip=$1
    sid=$2
    path=`./config/get.sh game.path $sid`
    ssh $ip "find $path/log/ -name \"gateway.log.1?\" -exec ls -sh {} \\; -exec rm -f {} \\;"
}

mem() {
    ip=$1
    sid=$2
    echo -n "[$sid] "
    path=`./config/get.sh game.path $sid`
    ssh $ip "source ~/.bash_profile; 
        cd $path;
        if [ -f game.pid ]; then
            pid=\`cat game.pid\`
            top -b -n 1 -p \$pid | grep node
        else
            echo Lost
        fi;"
}

###########################################################################
querylog(){
    if [ $# -lt 3 ]; then
        ./util/error.sh "$title" "param invalid"
        exit 1
    fi

    sid=$1
    userId=$2
    logPage=$3
    logWord=$4

    title="$cmd $sid"
    ip=`./config/get.sh server.query game $sid ip`
    if [ -z $ip ]; then
        echo "$tile sid invalid"
        exit 1
    fi

    exist=`./mysql/query_valid_server_field.sh $sid id`
    if [ -z $exist ]; then
        echo "$tile sid not exsit"
        exit 1
    fi

    path=`./config/get.sh game.path $sid`
    logFile=$path/log/game.log
    if [ $logPage -gt 0 ]; then
        logFile+=.$logPage
    fi

    if [ -z "$logWord" ]; then
        ssh $ip "cat $logFile | awk '{if(\$3 == $userId) print \$0}'"
    else
        ssh $ip "grep \"$logWord\" $logFile | awk '{if(\$3 == $userId) print \$0}'"
    fi
}

queryrecord(){
    if [ $# -lt 4 ]; then
        ./util/error.sh "$title" "param invalid"
        exit 1
    fi

    sid=$1
    openid=$2
    logDate=$3
    logType=$4

    title="$cmd $sid"
    ip=`./config/get.sh server.query game $sid ip`
    if [ -z $ip ]; then
        echo "$tile sid invalid"
        exit 1
    fi

    exist=`./mysql/query_valid_server_field.sh $sid id`
    if [ -z $exist ]; then
        echo "$tile sid not exsit"
        exit 1
    fi

    path=`./config/get.sh game.path $sid`
    ssh $ip "grep --no-filename \"$openid\" $path/log/record/*$logDate*.log | grep $logType"
}

list() {
    if [ 0 == $# -o "valid" == "$1" ]; then
        ./mysql/query_valid_server.sh "*"
    elif [ "all" = "$1" ]; then
        ./mysql/query.sh login "select * from server order by id"
    else
        ./mysql/query.sh login "select * from server where id=$1"
    fi
}

update() {
    sid=$1
    version=$2
    if [ -z "$version" ]; then
        warn "$title" "no version"
    fi

    if [ "all" = "$sid" ]; then
        sql="update global set value='$version' where name='version'"
        ./mysql/query.sh "login" "$sql"
        sql="update server set version=$version"
    else
        sql="update server set version=$version where id=$sid";
    fi
    result=`./mysql/query.sh "login" "$sql"`
}

open() {
    if [ $# -lt 2 ]; then
        warn "$title" "param invalid"
        exit 1
    fi

    sid=$1
    league_war_time=$2

    sql="update server set league_war_time=$league_war_time where id=$sid"
    result=`./mysql/query.sh "login" "$sql"`
    
    node ./config/update_server_d.js 
    node ./config/generator.js $sid
    cd "`./config/git_path.sh`"
    git add servers
    git commit -a -m "add game $sid"
    cd "$cwd"
    ./$process online fast.$sid
}

cleanMerged() {
    sid=$1
    minsid=${sid%%-*}
    maxsid=${sid##*-}
    ((sid=minsid-1))
    while [ $sid -lt $maxsid ]; do
        ((sid=sid+1))
        title="$cmd $sid"
        
        sql="select merged from server where id=$sid and (merged !=0 and merged !=id)"
        merged=`./mysql/query.sh login "$sql"`
        if [ -z $merged ]; then
            info "$title" "skip valid server"
            continue
        fi

        db_address=`./config/game_db_address.sh $sid`
        if [ -z $db_address ]; then
            warn "$title" "db address invalid"
            continue
        fi

        db_name=`./config/get.sh game.db_name $sid`
        if [ -z $db_name ]; then
            warn "$title" "db name invalid"
            continue
        fi
        ./util/debug.sh "$title" "$db_address/$db_name --quiet --eval 'db.dropDatabase()'" 
        mongo $db_address/$db_name --quiet --eval "db.dropDatabase()"

        merged_db_name=`./config/get.sh game.db_name $sid $merged`
        if [ -z $merged_db_name ]; then
            warn "$title" "merged db name invalid"
            continue
        fi
        ./util/debug.sh "$title" "$db_address/$merged_db_name --quiet --eval 'db.dropDatabase()'" 
        mongo $db_address/$merged_db_name --quiet --eval "db.dropDatabase()"
    done
}

reset() {
    ip=$1
    sid=$2

    stop $ip $sid

    db_address=`./config/game_db_address.sh $sid`
    db_name=`./config/game_db_name.sh $sid`
    mongo $db_address/$db_name ./mongo/user_reset.js

    start $ip $sid
}

###########################################################################

cwd=$(dirname $(readlink -f $0))
process=`basename $0`
cd "$cwd"

fullCmd=$1
cmd=$fullCmd
decorator="default"
if [ ${fullCmd:0:5} == "pure." ]; then
    decorator="pure"
    cmd=${fullCmd:5}
fi

dest=$2
title="$cmd $dest"

case "$cmd" in
    help|-help|--help|-h|--h)
        usage
        exit
    ;;
    online|status|restart|start|stop|recover|frestart|cleanlog|mem|reset) 
        if [ $# -lt 2 ]; then
            usage
            exit 1
        fi
    ;;
    querylog|queryrecord|update|open|cleanMerged)
        if [ $# -lt 2 ]; then
            usage
            exit 1
        fi
        $cmd $dest $3 $4 "$5"
        exit
    ;;
    list)
        title="$cmd"
        $cmd $2 $3 $4 $5
        exit
    ;;
    *)
        info "cmd $cmd" "unknown"
        usage
        exit 1
esac


if [ "all" == $dest ]; then
    hosts=(`./config/get.sh server.list game id`)
    for host in ${hosts[*]}; do
        ./$process $fullCmd host.$host $3 $4 $5
    done
elif [ "demon.all" == $dest ]; then
    hosts=(`./config/get.sh server.list game id`)
    pids=()
    for host in ${hosts[*]}; do
        ./$process $fullCmd host.$host $3 $4 $5 > demon.$host.log &
        pids+=($!)
    done

    echo "waiting ..."
    for pid in ${pids[*]}; do
        wait $pid
    done
    
    : > demon.log
    for host in ${hosts[*]}; do
        cat demon.$host.log >> demon.log
        rm demon.$host.log
    done

    echo "finished"
elif [ ${dest:0:5} == "host." ]; then
    host=${dest:5}
    ip=`./config/get.sh server.host.$host.ip`
    if [ -z $ip ]; then
        warn "$title" "invalid"
        exit 1
    fi

    host_sids=(`./config/get.sh server.sids game $host`)
    sids="0"
    for sid in ${host_sids[*]}; do
        sids+=","$sid
    done

    condition="id in ($sids)"
    sids=`./mysql/query_valid_server.sh id "$condition"`
    for sid in ${sids[*]}; do
        title="$cmd $sid"
        $cmd $ip $sid $3 $4 $5
    done
    title="$cmd $dest"
    info "$title" "finish"
elif [ ${dest:0:5} == "fast." ]; then
    sid=${dest:5}
    title="$cmd $sid"
    ip=`./config/get.sh server.query game $sid ip`
    if [ -z $ip ]; then
        warn "$title" "invalid"
        exit 1
    fi

    $cmd $ip $sid $3 $4 $5
else
    sid=$dest
    minsid=${sid%%-*}
    maxsid=${sid##*-}
    ((sid=minsid-1))
    while [ $sid -lt $maxsid ]; do
        ((sid=sid+1))
        title="$cmd $sid"
        ip=`./config/get.sh server.query game $sid ip`
        if [ -z $ip ]; then
            warn "$title" "invalid"
            exit 1
        fi
        
        exist=`./mysql/query_valid_server_field.sh $sid id`
        if [ -z $exist ]; then
            if [ $minsid -eq $maxsid ]; then
                warn "$title" "not exist"
                exit 1
            fi
            continue
        fi

        $cmd $ip $sid $3 $4 $5
    done
fi
